package com.spring.util.json;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Snippet {

	public static void main(String[] args) {
		JSONArray result = array2Tree(
				"[{\"value\":\"110\",\"label\":\"主席\",\"parentId\":\"0\"},{\"value\":\"111\",\"label\":\"副主席\",\"parentId\":\"110\"},{\"value\":\"112\",\"label\":\"总理\",\"parentId\":\"110\"},{\"value\":\"113\",\"label\":\"副总理1\",\"parentId\":\"112\"},{\"value\":\"114\",\"label\":\"副总理2\",\"parentId\":\"112\"},{\"value\":\"1\",\"label\":\"CEO\",\"parentId\":\"0\"},{\"value\":\"2\",\"label\":\"CTO\",\"parentId\":\"1\"},{\"value\":\"3\",\"label\":\"前端Leader\",\"parentId\":\"2\"},{\"value\":\"4\",\"label\":\"后端Leader\",\"parentId\":\"2\"},{\"value\":\"5\",\"label\":\"Java开发\",\"parentId\":\"3\"},{\"value\":\"6\",\"label\":\"Go开发\",\"parentId\":\"3\"},{\"value\":\"7\",\"label\":\"Vue开发\",\"parentId\":\"4\"},{\"value\":\"10\",\"label\":\"CFO\",\"parentId\":\"1\"},{\"value\":\"11\",\"label\":\"财务\",\"parentId\":\"10\"}]");
		System.out.println(result);
	}

	private static JSONArray array2Tree(String arrayJson) {
		JSONArray array = JSONArray.fromObject(arrayJson);
		// 生成hash，为遍历服务
		JSONObject hash = new JSONObject();
		for (Object o : array) {
			JSONObject object = (JSONObject) o;
			hash.put(object.getString("value"), object);
		}
		// 遍历出根节点
		JSONArray resultArr = new JSONArray();
		for (Object o : array) {
			JSONObject object = (JSONObject) o;
			if (hash.get(object.get("parentId").toString()) == null) {
				resultArr.add(object);
			}
		}

		// 生成树结构
		for (Object o : resultArr) {
			getJsonTree(array, (JSONObject) o);
		}
		return resultArr;
	}

	/**
	 * 递归将原始数据转换成树结构
	 *
	 * @param jsonArray 原始数据
	 * @param object    目标对象
	 */
	private static void getJsonTree(JSONArray jsonArray, JSONObject object) {
		JSONArray tempArray = JSONArray.fromObject("[]");
		for (Object o : jsonArray) {
			JSONObject tempObj = (JSONObject) o;
			if (tempObj.get("parentId").equals(object.get("value"))) {
				tempArray.add(tempObj);
			}
		}
		jsonArray.removeAll(tempArray);
		for (Object o : tempArray) {
			getJsonTree(jsonArray, (JSONObject) o);
		}
		if (tempArray.size() != 0)
			object.put("children", tempArray);
	}
}
